import { login, getUserInfo, getUserDetailById } from '@/api/user.js'
import { getToken, setToken, removeToken, setTimeStamp } from '@/utils/auth.js'
import { resetRouter, constantRoutes } from '@/router'
const state = {
  token: getToken(),
  userInfo: {},
  menu: []
}
const mutations = {
  setToken(state, token) {
    state.token = token
    setToken(token)
  },
  removeToken(state) {
    state.token = null
    removeToken()
  },
  setUserInfo(state, result) {
    state.userInfo = { ...result }
  },
  removeUserInfo(state) {
    state.userInfo = {}
  },
  setMenu(state, payload) {
    state.menu = [...constantRoutes, ...payload]
  }
  // logout() {
  //   this.commit('removeToken')
  //   this.commit('removeUserInfo')
  // }
}
const actions = {
  async login(context, data) {
    const result = await login(data)
    context.commit('setToken', result)
    setTimeStamp()
  },
  async getUserInfo(context) {
    const result = await getUserInfo()
    const baseInfo = await getUserDetailById(result.userId)
    const baseResult = { ...result, ...baseInfo }
    context.commit('setUserInfo', baseResult)
    return baseResult
  },
  logout(context) {
    context.commit('removeToken')
    context.commit('removeUserInfo')
    resetRouter()
  }
}
export default {
  namespaced: true,
  state,
  mutations,
  actions
}

